import { Component, OnInit, ViewChild } from '@angular/core';
import { UploadFileStatusEnum, MessageService, UploadHttpRequestOptions, UploadComponent } from '@iux/live';
import { result } from 'lodash';
import { HttpClient, HttpEventType, HttpParams } from '@angular/common/http';
import { tap, last, switchMap, catchError } from 'rxjs/operators';
import { throwError, of } from 'rxjs';

@Component({
  selector: 'app-demo8',
  templateUrl: './demo8.component.html',
  styles: []
})
export class Demo8Component implements OnInit {
  fileParams = {
    from: 'cxd'
  };
  httpParams = (file) => {
    return {
      // 当前只解析这两个字段
      params: new HttpParams().set('name', file.name),
      responseType: 'blob'
    }
  };
  @ViewChild(UploadComponent, { static: false}) lvUpload: UploadComponent;
  constructor(private messageService: MessageService, private http: HttpClient) { }

  ngOnInit() {
  }

  change(e) {
    console.log(e);
    if (e.action === UploadFileStatusEnum.ERROR) {
      e.files[0]['errorTip'] =  e.files[0].error.message || '自定义上传失败的原因';
      this.messageService.error(result(e, 'file.error.message') || '上传失败！');
    }
  }

  customUpload = (options: UploadHttpRequestOptions) => {
    return this.http.request(this.lvUpload.getHttpRequest(options)).pipe(
      tap(event => this.setProgressEvent(event, options)),
      last(),
      switchMap(res => this.uploadHook(res)),
      tap(res => {
        options.onSuccess(res, options.file);
      }),
      catchError(error => {
        options.onError(error, options.file);
        return throwError((typeof error === 'string') ? {
          message: error
        } : error);
      })
    );
  }

  setProgressEvent(event: any, options: UploadHttpRequestOptions) {
    const type = event.type, file = options.file;
    if (type === HttpEventType.Sent) {
      options.onSend(file);
    } else if (type === HttpEventType.UploadProgress) {
      let progress = Math.round(100 * event['loaded'] / event['total']);
      options.onProgress(progress, file);
    }
  }

  uploadHook(response: any) {
    const imageSize = response.body.size, errorMsg = '仅支持300*300大小图片';

    if (imageSize.width !== 300 && imageSize.height.height !== 300) {
      this.messageService.error(errorMsg);
      return throwError(errorMsg);
    }
    return of(response);
  }

}
